Ext.define('DragonApp.view.server.Controller', {
    extend: 'DragonApp.view.foundation.ViewController',
    alias: 'controller.server',

    requires: [
        'DragonApp.view.server.Window',
        'DragonApp.util.Msg'
    ],
    /**
     * 刷新服务器
     * @DateTime 2017-12-14
     * @param    {[type]} button [description]
     * @param    {[type]} e [description]
     * @param    {[type]} options [description]
     * @return   {[type]}
     */
    onRefresh: function(button, e, options) {

        var store = Ext.data.StoreManager.lookup('jsonPServerStore');
        store.loadPage(1);
    },
    /**
     * 创建窗体(新建、编辑)
     * @DateTime 2017-12-14
     * @param    {[type]} record [description]
     * @return   {[type]}
     */
    createDialog: function(record) {

        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: 'pop_window_server',
            height: 290,
            width: 400,
            viewModel: {
                data: {
                    title: record ? '编辑' : '新增'
                }
            }
        });

        //========
        //表单类型
        //========
        var typeField = Ext.ComponentQuery.query('hiddenfield#formtype')[0];

        //========
        //类型赋值
        //========
        if (!Ext.isEmpty(record)) {
            me.dialog.down("form").loadRecord(record);
            typeField.setValue('edit');
        } else {
            typeField.setValue('new');
        }

        me.dialog.show();
    },
    /**
     * 删除服务器记录
     * @DateTime 2017-12-14
     * @param    {[type]} button [description]
     * @param    {[type]} e [description]
     * @param    {[type]} options [description]
     * @return   {[type]}
     */
    onDelete: function(button, e, options) {

        var record = button.getWidgetRecord();

        var formValue = {};
        formValue.id = record.get('id');

        var store = Ext.data.StoreManager.lookup('jsonPServerStore');

        Ext.Msg.show({
            title: '提示',
            msg: '删除这条记录?',
            buttons: Ext.Msg.YESNO,
            icon: Ext.Msg.QUESTION,
            fn: function(buttonId) {
                if (buttonId == 'yes') {
                    Ext.data.JsonP.request({
                        url: DragonApp.ux.config.Config.getUrl('/index/Server/delete/'),
                        async: false,
                        params: formValue,
                        callbackKey: "callback",
                        success: function(result) {

                            DragonApp.util.Msg.showToast(result.msg);

                            switch (result.success) {
                                case true:
                                    store.loadPage(1);
                                    break;
                            }
                        },
                        failure: function(result) {
                            Ext.Msg.alert('提示', result);
                        }
                    });
                }
            }
        });
    },
    /**
     * 保存新建记录/更新记录
     * @DateTime 2017-12-14
     * @param    {[type]} button [description]
     * @param    {[type]} e [description]
     * @param    {[type]} options [description]
     * @return   {[type]}
     */
    onSave: function(button, e, options) {

        var window = this.lookupReference('server_window');
        var form = this.lookupReference('server_form').getForm();

        var me = this;
        var store = Ext.data.StoreManager.lookup('jsonPServerStore');

        var formValue = form.getValues();

        //配置(表单类型)提交网址
        var url = ('new' == formValue.formtype) ? '/index/Server/add/' : '/index/Server/update/';

        window.mask('提交中...');

        if (form.isValid()) {

            Ext.data.JsonP.request({
                url: DragonApp.ux.config.Config.getUrl(url),
                async: false,
                params: formValue,
                callbackKey: "callback",
                success: function(result) {
                    window.unmask();
                    DragonApp.util.Msg.showToast(result.msg);

                    switch (result.success) {
                        case true:
                            form.destroy();
                            window.destroy();
                            store.loadPage(1);
                            break;
                    }
                },
                failure: function(result) {
                    window.unmask();
                    Ext.Msg.alert('提示', result);
                }
            });
        }
    },
    /**
     * 根据服务器ID，操作服务器
     * @DateTime 2017-12-14
     * @param    {[type]} server_id [description]
     * @param    {[type]} value [description]
     * @return   {[type]}
     */
    onServerChange: function(server_id,value){

      var grid = this.getView();
      var store = grid.getStore();

      Ext.Ajax.request({
        method: 'GET',
        url: DragonApp.ux.config.Config.getUrl('/index/Server/update/'),
        params: {
          id: server_id,
          status: value
        },
        success: function(response, opts) {
          var obj = Ext.decode(response.responseText);
          if(true == obj.success){
            store.reload();
            DragonApp.util.Msg.showToast(obj.msg);
          }
        },

        failure: function(response, opts) {
          console.log('server-side failure with status code ' + response.status);
        }
       });
    },
    /**
     * 服务器状态切换响应
     * @DateTime 2017-12-14
     * @param    {[type]} grid [description]
     * @param    {[type]} rowIndex [description]
     * @param    {[type]} colIndex [description]
     * @param    {[type]} item [description]
     * @param    {[type]} rec [description]
     * @return   {[type]}
     */
    onServerOperationReq: function(grid, rowIndex, colIndex, item, rec) {

      var server,store,record,status;
      store = grid.getStore();
      record = store.getAt(rowIndex);
      server_id = record.getData().id;

          switch (item.itemId) {
              case 'OPEN':
              status = 1;
          break;
              case 'CLOSE':
              status = 0;
          break;
              case 'PAUSE':
              status = 2;
          break;
          }
      this.onServerChange(server_id,status);
    },

    /**
     * 批量请求
     * @DateTime 2017-12-14
     * @param    {[type]} button [description]
     * @param    {[type]} e [description]
     * @param    {[type]} options [description]
     * @return   {[type]}
     */
    onBatRequest: function(button, e, options) {

        var status;

        switch (button.itemId) {
            case 'open':
            status = 1;
        break;
            case 'close':
            status = 0;
        break;
            case 'pause':
            status = 2;
        break;
        }

        this.onBatOperate(status);
    },

    /**
     * 批量操作服务器
     * @DateTime 2017-12-14
     * @param    {[type]} status [description]
     * @return   {[type]}
     */
    onBatOperate: function(status) {

        var grid = this.getView();
        var store = grid.getStore();

        var arr = this.getSelections();
        var param = JSON.stringify(arr);

        if( true == Ext.isEmpty(arr) ){
            DragonApp.util.Msg.showToast('操作服务器，请先勾选列表复选框');
            return;
        }else{
            Ext.Ajax.request({
                method: 'GET',
                url: DragonApp.ux.config.Config.getUrl('/index/Server/batUpdate/'),
                params: {
                  id: param,
                  status: status
                },
                success: function(response, opts) {
                  var obj = Ext.decode(response.responseText);
                  if(true == obj.success){
                    store.reload();
                    DragonApp.util.Msg.showToast(obj.msg);
                  }else{
                    DragonApp.util.Msg.showToast(obj.msg);
                  }
                },

                failure: function(response, opts) {
                  console.log('server-side failure with status code ' + response.status);
                }
           });
        }


    },

    /**
     * 批量获取服务器记录ID
     * @DateTime 2017-12-14
     * @return   {[type]}
     */
    getSelections: function() {

        var grid = this.getView();

        var records = grid.getSelectionModel().getSelection();

        //批量获取ID
        var arr = [];

        records.forEach(function(item) {
            arr.push(item.id);
        });

        return arr;
    },
    /**
     * 服务器状态渲染
     * @DateTime 2017-12-14
     * @param    {[type]} value [description]
     * @return   {[type]}
     */
    statusRender: function(value) {
        switch (value) {
            case '0':
                return '关服';
            case '1':
                return '开服';
            case '2':
                return '停服';
        }
    }
});